(function() {

	var BusCon = require("../../core/bus/_con");
	var AchCon = require("../../core/ach/_con");
	var db = require("../../core/db/index");
	var config = require("../../core/_include/config");
	var SpreadsheetWriter = require('../../my_modules/pyspreadsheet').SpreadsheetWriter;
	var ResponObj = require("../_include/responObj");
	var myfs = require("../_include/fs");
	var fs = require("fs");
	var theme = require("./theme");
	var role = require("./role");
	var helper = require("../../core/_include/helper");
	var http = require('http');
	var phoneCode = require("./phone_code");

	module.exports = {
		prefix: "/bus",
		"post": {
			//注册一个商家
			//并为此商家建立一个独立的站点文件夹
			/*
			 * body:{bus.info}
			 * query:{
			 *     theme:"theme_name"
			 * }
			 }
			 */
			"/register_with_domain_build": function() {
				var body = this.request.body;
				var bus_name = body.name.trim();
				if (!(body.password && body.confirm_password && body.domain)) {
					throwCusError("表单不完整");
				} else if (body.password !== body.confirm_password) {
					throwCusError("两次密码输入不匹配");
				} else if (body.phone_code !== phoneCode.get(body.mobile_phone)) {
					console.log(body.phone_code, phoneCode.get(body.mobile_phone))
					throwCusError("验证码错误");
				} else {
					//账号注册到数据库中
					var bus = new BusCon(body);
					var domain = body.domain;
					bus.initDomain(domain, body.is_secondary_domain);
					this.body = ResponObj("json", BusCon.get(bus._id));
				}
			},
			"/login": function() {
				var query = this.request.query;
				var form_data = this.request.body;
				var bus = BusCon.login(form_data);
				// if (!query.ignore_origin && !bus.checkOrigin(this.request.headers["origin"])) {
				// 	throwCusError("请在您自己的店铺站点后台登录");
				// }
				//进入已登录状态
				role.loginBus(this, bus);
				this.body = ResponObj("json", bus);
			},
			//商家退出登录
			"/loginout": function() {
				var loginerHash = this.cookies.get("bus_loginSession");
				var bus_id = this.cookies.get("bus_login_id");
				var bus = role.getBus(this);
				var loginInfo = db.find_by_id(config.dbname.loginHash, bus_id);
				if (loginInfo) {
					var removerIndex;
					loginInfo.loginers_arr.some(function(item, index) {
						if (item.hash === loginerHash) {
							removerIndex = index;
							return true;
						}
					});
					if (removerIndex === +removerIndex) {
						loginInfo.loginers_arr.splice(removerIndex, 1);
						db.update(config.dbname.loginHash, bus_id, loginInfo);
					}
				}
				//清空Cookie
				this.cookies.set("bus_loginSession", "");
				this.cookies.set("bus_login_id", "");
				this.body = ResponObj("json", "商家下线成功");
			},
		},
		"get": {
			"/byId/:bus_id": function() {
				//商家名不分大小写，同文件夹
				var bus_id = this.params.bus_id; //.toLowerCase();
				var result;
				// if (name.indexOf(config.dbIdPrefix.bus)===0) {
				result = db.find_by_id(config.dbname.bus, bus_id);
				// }
				if (!result) {
					throwCusError("找不到指定商家");
				}
				this.body = ResponObj("json", result);
			},
			//获取当前登录的商家信息
			"/": function() {
				var bus = role.getBus(this);
				this.body = ResponObj("json", bus);
			},
			//获取商家注册的短信验证码
			"/registerCode": function() {
				var self = this;
				var query = self.request.query;
				var mobile_phone = query.mobile_phone;
				// console.log("mobile_phone:", mobile_phone);
				if (!mobile_phone) {
					throwCusError("参数错误");
				}
				if (!helper.phone(mobile_phone)) {
					throwCusError("手机号码格式错误")
				}
				phoneCode.send("商家注册", mobile_phone);
				this.body = ResponObj("string", "验证码发送成功");
			},
			//获取商家修改手机号的短信验证码
			"/updateCode": function() {
				var self = this;
				var query = self.request.query;
				var mobile_phone = query.mobile_phone;
				// console.log("mobile_phone:", mobile_phone);
				if (!mobile_phone) {
					throwCusError("参数错误");
				}
				if (!helper.phone(mobile_phone)) {
					throwCusError("手机号码格式错误")
				}
				phoneCode.send("商家修改", mobile_phone);
				this.body = ResponObj("string", "验证码发送成功");
			},
			//商家退出登录
			"/loginout": function() {
				var bus = role.getBus(this);
				//删除loginHash中同商家名的信息
				db.remove_list(config.dbname.loginHash, {
					bus_id: bus._id
				});
				//清空Cookie
				this.cookies.set("loginSession", "");
				this.body = ResponObj("json", "商家下线成功");
			},
			"/ach/xlsx": function() {
				var bus = role.getBus(this);
				var query = this.request.query;
				var start_time = +query.start_time;
				var end_time = +query.end_time;
				var achs = bus.getAchs(0, 0, function(ach) {
					// console.log(ach.info.state == AchCon.STATE.交易完成, ach.create_time, start_time, end_time);
					return ach.info.state == AchCon.STATE.交易完成 && ach.create_time > start_time && ach.create_time < end_time;
				});
				var ws_name = new Date(start_time).format("yyyy-MM-dd") + "~" + new Date(end_time).format("yyyy-MM-dd");
				var fileName = "【{0}】{1}订单报表.xlsx".format(bus.info.name, ws_name);
				var writer = new SpreadsheetWriter(fileName);
				writer.addSheet(ws_name);

				writer.addFormat("ach_id", {
					font: {
						bold: true
					},
					alignment: "middle"
				});
				writer.addFormat("merge_cell", {
					alignment: "middle"
				});
				writer.addFormat("title", {
					font: {
						bold: true
					},
					alignment: "center",
					fill: {
						foregroundColor: "yellow"
					}
				});

				/*TABLE HEAD*/
				writer.append(["订单号", "商品名称", "购买数量", "商品单价", "合计", "订单原价格", "订单优惠额度", "订单抵扣额度", "订单自改价格", "最终消费"], "title");
				/*TD WIDTH*/
				writer.setColumn("A:A", 27);
				writer.setColumn("B:B", 20);
				writer.setColumn('F:J', 13);

				var row_num = 1;

				function _merge_line(C, row_num, len, value, format) {
					writer.merge(C + (row_num + 1) + ":" + C + (row_num + len), value, format);
				};

				function _sing_line(C, row_num, len, value, format) {
					writer.write(C + (row_num + len), value, format);
				};
				achs.forEach(function(ach) {
					var row_num_bak = row_num;
					var len = ach.info.goods_info.length

					ach.info.goods_info.forEach(function(goods_info, index) {
						row_num += 1;
						var write_merge = index == 0;
						var youhui_cash = (ach.sou_cash - (ach.cash + ach.bind_acc || 0)) || 0;
						var dikou_cash = (ach.bind_acc) || 0;
						if (len > 1) {
							var write_handle = _merge_line;
						} else {
							write_handle = _sing_line;
						}
						//合并的单元格默认是合并后最后面的那个格子，如果提前写会让后面的写不上，所以一定要写最后一行的时候写
						if (write_merge) {
							write_handle("A", row_num_bak, len, ach._id /*, "ach_id"*/ ); //订单号
							write_handle("F", row_num_bak, len, ach.sou_cash /*, "merge_cell"*/ ); //订单原价格
							write_handle("G", row_num_bak, len, youhui_cash /*, "merge_cell"*/ ); //订单优惠额度
							write_handle("H", row_num_bak, len, dikou_cash /*, "merge_cell"*/ ); //订单抵扣额度
							write_handle("I", row_num_bak, len, ach.cus_cash || 0 /*, "merge_cell"*/ ); //订单自改价格
							write_handle("J", row_num_bak, len, ach.finally_cash = ach.cus_cash || ach.cash /*, "merge_cell"*/ ); //最终消费
						}
						var sheet_array = [goods_info.goods.goods_name, goods_info.num, goods_info.goods.price, "=C" + row_num + "*D" + row_num];
						writer.write("B" + row_num, sheet_array);
					});
				});

				//统计
				var last_row_num = row_num + 2;
				writer.write("G" + last_row_num, "订单量：", "title");
				writer.write("H" + last_row_num, achs.length);
				writer.write("I" + last_row_num, "总计：", "title");
				writer.write("J" + last_row_num, "=SUM(J2:J" + row_num + ")");
				writer.save();
				// this.response.sendFile(fileName);
				// fs.unlink(fileName);
				this.body = ResponObj("json", fileName);
			},
			// 获取首页轮播图
			"/home_imgs/:bus_id": function() {
				var bus_id = this.params.bus_id;
				var bus = BusCon.get(bus_id);
				if (bus) {
					this.body = ResponObj("json", bus.config.home_imgs);
				} else {
					throwCusError("找不到指定商家")
				}
			}
		},
		"put": {
			"/info": function() {
				var bus = role.getBus(this);
				bus.setInfo(this.request.body);
				this.body = ResponObj("json", bus);
			},
			"/config": function() {
				var bus = role.getBus(this);
				var body = this.request.body;
				var data = body.data;
				var type = body.type;
				var key = body.key;
				var mix_data = body.mix_data;
				var keys = body.keys;
				if (type === "json") {
					try {
						if (key) {
							data = JSON.parse(data)
						} else if (keys) {
							mix_data = JSON.parse(mix_data);
						}
					} catch (e) {
						throwCusError("参数错误")
					}
				}

				if (key && data) {
					bus.setConfig(key, data);
				} else if (mix_data && keys) {
					bus.setMixConfig(keys, mix_data);
				} else {
					throwCusError("参数错误")
				}
				this.body = ResponObj("json", bus);
			},
			"/password": function() {
				var bus = role.getBus(this);
				var body = this.request.body;
				bus.setPassword(body.old_password, body.new_password);
				this.body = ResponObj("json", bus);
			},
			"/mobile_phone": function() {
				var bus = role.getBus(this);
				var body = this.request.body;
				if (body.phone_code !== phoneCode.get(body.mobile_phone)) {
					console.log(body.phone_code, phoneCode.get(body.mobile_phone))
					throwCusError("验证码错误");
				}
				bus.setMobilePhone(body.mobile_phone);
				this.body = ResponObj("json", bus);
			},
			"/lbs": function() {
				var bus = role.getBus(this);
				var body = this.request.body;
				var lat = body.lat;
				var lon = body.lon;
				if (!(lat && lon)) {
					throwCusError("参数错误")
				}
				bus.setLBS(lat, lon);
				this.body = ResponObj("json", bus);
			}
		}
	}

}());